from django.shortcuts import render, HttpResponse, redirect, reverse
from django.http import JsonResponse
from io import BytesIO
from django.db.models import Q
import uuid
import datetime

from web.forms.account import RegisterForm, SendSmsForm, LoginSmsForm, LoginForm
from web import models


def register(request):
    """注册"""
    if request.method == 'GET':
        form = RegisterForm()
        return render(request, "register.html", {"form": form})

    form = RegisterForm(data=request.POST)
    if form.is_valid():
        # 保存生成一个用户对象
        instance = form.save()
        # 创建交易记录
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=models.PricePolicy.objects.filter(category=1, title="个人免费版").first(),
            count=0,
            price=0,
            start_datetime=datetime.datetime.now(),
        )
        return JsonResponse({"status": True, "data": "/login/"})
    else:
        return JsonResponse({"status": False, "err": form.errors})


def send_sms(request):
    """发送短信"""
    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({"status": True})
    return JsonResponse({"status": False, "err": form.errors})


def login_sms(request):
    """短信登录"""
    if request.method == 'GET':
        form = LoginSmsForm()
        return render(request, "login_sms.html", {"form": form})

    form = LoginSmsForm(data=request.POST)
    if form.is_valid():
        # 用户输入正确，登录成功
        mobile_phone = form.cleaned_data['mobile_phone']

        # 把用户名写入到session中
        user_object = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        request.session['user_id'] = user_object.id
        request.session.set_expiry(60 * 60 * 24 * 14)

        return JsonResponse({"status": True, "data": "/index/"})
    return JsonResponse({"status": False, "err": form.errors})


def login(request):
    """用户名和密码登录"""
    if request.method == "GET":
        form = LoginForm(request)
        return render(request, "login.html", {"form": form})

    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data["username"]
        password = form.cleaned_data["password"]

        user_obj = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()
        if user_obj:
            # 用户名 密码 正确
            # 登录成功为止1
            request.session['user_id'] = user_obj.id
            request.session.set_expiry(60 * 60 * 24 * 14)

            return redirect("index")
        form.add_error("username", "用户名或密码错误")

    return render(request, "login.html", {"form": form})


def image_code(request):
    """图片验证码"""
    from utils.image_code import check_code
    img_obj, code = check_code()

    # 把图片验证码写入session中
    request.session['image_code'] = code
    # 设置图片验证码过期时间
    request.session.set_expiry(60)

    print(code)

    bytes_io = BytesIO()
    img_obj.save(bytes_io, "png")

    return HttpResponse(bytes_io.getvalue())


def logout(request):
    request.session.flush()
    return redirect("index")
